import React, { Component } from 'react'
import {
  StyleSheet,
  View,
  ScrollView,
  Text,
  TextInput,
  TouchableOpacity,
  DeviceEventEmitter,
  AsyncStorage,
} from 'react-native'

import Base from './Base'
import {
  NavigationActions,
  createAction,
  getBorderWidth,
  setAsyncStorage,
  removeAsyncStorage,
} from '../utils'

import Icon from 'react-native-vector-icons/Ionicons'
import { toast } from '../utils/toast'
import Button from '../component/Button'
import RootView from '../component/RootView'
import * as authService from '../services/auth'

class CloseButton extends Component {
  render() {
    return (
      <TouchableOpacity onPress={() => this.props.onPress()}>
        <View
          style={{ flex: 1, justifyContent: 'center', paddingHorizontal: 16 }}
        >
          <Icon name="ios-close" size={36} />
        </View>
      </TouchableOpacity>
    )
  }
}

class Signin extends Base {
  constructor(props) {
    super(props)
    this.state = {
      count: 0,
    }
    this.interval = null
  }
  static navigationOptions = ({ navigation }) => ({
    title: '登录',
    headerLeft: (
      <CloseButton
        onPress={() => {
          navigation.dispatch(NavigationActions.back())
        }}
      />
    ),
    headerStyle: {
      backgroundColor: 'white',
      borderBottomWidth: 0,
      shadowColor: 'transparent',
      elevation: 1,
    },
    headerRight: <View />,
  })
  sendCaptcha = () => {
    const mobile = this.refs.mobile._lastNativeText
    this.setState({ fetching: true })
    authService
      .captcha({ mobile })
      .then(data => {
        this.onGetCaptcha()
      })
      .catch(e => {
        this.setState({ fetching: false })
        toast(e.msg)
      })
  }
  onGetCaptcha = () => {
    let count = 59
    this.setState({ count, fetching: false })
    this.interval = setInterval(() => {
      count -= 1
      this.setState({ count })
      if (count === 0) {
        clearInterval(this.interval)
      }
    }, 1000)
  }
  onLogin = () => {
    this.setState({ fetching: true })
    const mobile = this.refs.mobile._lastNativeText
    const captcha = this.refs.password._lastNativeText
    authService
      .login({ mobile, captcha })
      .then(data => {
        if (data.code) {
          this.setState({
            fetching: false,
          })
          toast(data.msg)
          return
        }

        AsyncStorage.setItem('APP_TOKEN', JSON.stringify(data.data), error => {
          if (!error) {
            DeviceEventEmitter.emit('account.reload')
            setTimeout(() => {
              this.setState({ fetching: false })
              this.goBack()
            }, 300)
          }
        })
      })
      .catch(e => {
        this.checkError(e)
      })
  }

  componentWillUnmount() {
    removeAsyncStorage('Signin')
    clearInterval(this.interval)
  }
  componentDidMount() {
    const { key } = this.props.navigation.state
    console.log(key)
    setAsyncStorage('Signin', key)
  }

  render() {
    const { fetching, count } = this.state

    return (
      <RootView fetching={fetching} style={styles.container}>
        <ScrollView>
          <View
            style={{ marginTop: 10, backgroundColor: '#fff', paddingLeft: 16 }}
          >
            <View style={styles.item}>
              <View style={styles.label}>
                <Text>{'账号'}</Text>
              </View>
              <View style={{ flex: 1 }}>
                <TextInput
                  ref="mobile"
                  underlineColorAndroid="transparent"
                  keyboardType={'numeric'}
                  style={styles.textInput}
                  placeholder="手机号码"
                  placeholderTextColor="#aaa"
                />
              </View>
              <View
                style={{
                  height: 28,
                  justifyContent: 'center',
                  paddingHorizontal: 12,
                }}
              >
                {count ? (
                  <Text style={{ color: '#999' }}>{count}秒后可重发</Text>
                ) : (
                  <TouchableOpacity onPress={() => this.sendCaptcha()}>
                    <Text style={{ color: '#0398ff' }}>获取验证码</Text>
                  </TouchableOpacity>
                )}
              </View>
            </View>
            <View style={styles.item}>
              <View style={styles.label}>
                <Text>{'验证码'}</Text>
              </View>
              <View style={{ flex: 1 }}>
                <TextInput
                  ref="password"
                  underlineColorAndroid="transparent"
                  keyboardType={'numeric'}
                  style={styles.textInput}
                  placeholder="6位验证码"
                  placeholderTextColor="#aaa"
                />
              </View>
            </View>
          </View>

          <Button
            style={{
              marginTop: 20,
              marginHorizontal: 16,
              borderRadius: 3,
              overflow: 'hidden',
            }}
            onPress={() => {
              this.onLogin()
            }}
          >
            <View
              style={{
                flex: 1,
                height: 40,
                backgroundColor: '#56d176',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <Text style={{ color: '#fff' }}>{'确定'}</Text>
            </View>
          </Button>
        </ScrollView>
      </RootView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  item: {
    borderBottomWidth: getBorderWidth(),
    borderBottomColor: '#f0f0f0',
    paddingVertical: 10,
    flexDirection: 'row',
  },
  active: {
    borderColor: '#81c2ff',
    color: '#0096ff',
  },
  label: {
    minWidth: 45,
    height: 28,
    justifyContent: 'center',
  },
  textInput: {
    flex: 1,
    paddingVertical: 0,
    height: 30,
    fontSize: 14,
    paddingHorizontal: 10,
  },
})

export default Signin
